from PySide6.QtWidgets import (
    QFrame, QLabel, QTextEdit, QPushButton, 
    QVBoxLayout, QHBoxLayout, QRadioButton, QComboBox, QMessageBox,QCompleter
)
from PySide6.QtCore import Qt,QTimer,Signal,QStringListModel
from qfluentwidgets import SearchLineEdit  # 确保已安装 qfluentwidgets
import sqlite3

class AddPetBattleWidget(QFrame):
    petSelected=Signal(str)
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.db = parent.db
        self.setObjectName("AddPetBattleWidget")
        self.setup_ui()
        self.setup_autocompletion()

# region ui  初始化  
    def setup_ui(self):
        # 主垂直布局
        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.setContentsMargins(10, 10, 10, 10)
        self.mainLayout.setSpacing(15)
        
        # 1. 搜索框
        self.searchEdit = SearchLineEdit(self)
        self.searchEdit.setPlaceholderText("搜索宠物对战信息...")
        self.mainLayout.addWidget(self.searchEdit)
        self.searchEdit.searchSignal.connect(self.select_battle_pet_info)
        
        
        # 2. 水平布局1（包含敌方和我方选择）
        self.hLayout1 = QHBoxLayout()
        self.mainLayout.addLayout(self.hLayout1)
        
        # 敌方选择部分
        self.enemyLayout = QHBoxLayout()
        self.enemyLabel = QLabel("敌方:", self)
        self.enemyRadio = QRadioButton("敌方", self)
        self.enemyLayout.addWidget(self.enemyLabel)
        self.enemyLayout.addWidget(self.enemyRadio)
        self.hLayout1.addLayout(self.enemyLayout)
        
        # 我方选择部分
        self.allyLayout = QHBoxLayout()
        self.allyLabel = QLabel("我方:", self)
        self.allyRadio = QRadioButton("我方", self)
        self.allyLayout.addWidget(self.allyLabel)
        self.allyLayout.addWidget(self.allyRadio)
        self.hLayout1.addLayout(self.allyLayout)
        
        # 确保默认选中一个
        self.enemyRadio.setChecked(True)
        
        # 3. 水平布局2（包含顺序和处理情况）
        self.hLayout2 = QHBoxLayout()
        self.mainLayout.addLayout(self.hLayout2)
        
        # 上场顺序部分
        self.orderLayout = QHBoxLayout()
        self.orderLabel = QLabel("上场顺序:", self)
        self.orderCombo = QComboBox(self)
        self.orderCombo.addItems(["后发上场", "同时上场", "提前站场"])
        self.orderLayout.addWidget(self.orderLabel)
        self.orderLayout.addWidget(self.orderCombo)
        self.hLayout2.addLayout(self.orderLayout)
        
        # 处理情况部分
        self.actionLayout = QHBoxLayout()
        self.actionLabel = QLabel("处理情况:", self)
        self.actionCombo = QComboBox(self)
        self.actionCombo.addItems(["击杀", "删废", "互废","限制"])
        self.actionLayout.addWidget(self.actionLabel)
        self.actionLayout.addWidget(self.actionCombo)
        self.hLayout2.addLayout(self.actionLayout)
        
        # 4. 文本编辑区域
        self.textEdit = QTextEdit(self)
        self.textEdit.setPlaceholderText("输入对战策略详细信息...")
        self.textEdit.setMinimumHeight(150)
        self.mainLayout.addWidget(self.textEdit, 1)
        
        # 5. 提交按钮
        self.submitButton = QPushButton("提交对策", self)
        self.submitButton.setObjectName("primaryButton")
        self.submitButton.setMinimumSize(120,60)
        self.mainLayout.addWidget(self.submitButton, 0, Qt.AlignRight)
        self.submitButton.clicked.connect(self.input_battle_pet)
# endregion

# region 提交对战策略
    def input_battle_pet(self):
        """
        输入对战记录
        """
        try:
            # 获取界面数据
            opponent_pet = self.enemyRadio.text()
            our_pet = self.allyRadio.text()
            turn_order = self.orderCombo.currentIndex()-1
            outcome = self.actionCombo.currentText()
            description = self.textEdit.toPlainText()

            # 基础校验
            if not opponent_pet or not our_pet:
                raise ValueError("请先选择敌方和我方宠物")

            # 调用数据库插入方法
            self.db.insert_battle_strategy(
                opponent_pet_name=opponent_pet,
                our_pet_name=our_pet,
                turn_order=int(turn_order),
                outcome=outcome,
                strategy_description=description,
                success_count=0  
            )

            # 清空输入
            self.allyRadio.setText("")
            self.textEdit.clear()
            QMessageBox.information(self, "提示", "战斗策略录入成功")

        except ValueError as e:
            print("输入不完整:", e)
            self._show_error("输入不完整", str(e))
        except sqlite3.Error as e:
            print("数据库错误:", e)
            self._show_error("数据库错误", f"策略保存失败: {str(e)}")
        except Exception as e:
            print("系统错误:", e)
            self._show_error("系统错误", str(e))
# endregion

# region 输入框的补全功能
    def setup_autocompletion(self):
        """设置自动补全功能（优化版）"""
        # 1. 初始化自动补全
        self.model = QStringListModel()

        self.completer = QCompleter(self)        
        self.completer.setModel(self.model)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setFilterMode(Qt.MatchContains)
        
        self.searchEdit.setCompleter(self.completer)
        
        self.searchEdit.textChanged.connect(self.update_autocompletion)
        
    def update_autocompletion(self,search_text):
        """从数据库获取自动补全数据"""
        if not search_text:
            self.model.setStringList([])
            return
            
        try:
            # 优化：只查询名字字段
            pet_infos = self.db.search_pets(name=search_text, all_pets=True) 
            
            # 存储新的自动补全项（名字倒序）
            unique_names = []
            for pet_info in reversed(pet_infos):
                pet_name = pet_info[0]  # 假设第一个元素是名字
                unique_names.append(pet_name)
            
            # 更新模型
            self.model.setStringList(unique_names)
        
            # 安全触发下拉框显示（关键修改）
            if unique_names and self.searchEdit.isEnabled():
                QTimer.singleShot(50, self.safe_show_completer)
            
            # 可选：触发信号
            self.petSelected.emit(search_text)
                
        except Exception as e:
            print(f"自动补全查询错误: {e}")

    def safe_show_completer(self):
        """安全显示补全下拉框"""
        # 双重检查控件有效性
        if (self.searchEdit.isVisible() and 
            self.searchEdit.isEnabled() and
            not self.searchEdit.text().strip() and
            self.completer):
            
            # 设置焦点到搜索框（确保下拉框能显示）
            self.searchEdit.setFocus()
            
            # 安全调用complete()
            try:
                if len(self.completion_model.stringList()) > 0:
                    self.completer.setCompletionPrefix(self.searchEdit.text())
                    self.completer.complete()
            except RuntimeError:
                # 处理对象已被销毁的情况
                pass
# endregion

# region 选择宠物
    def select_battle_pet_info(self):
        """
        选择宠物
        """
        selected_pet_name = self.searchEdit.text()
        if self.enemyRadio.isChecked():
            self.enemyRadio.setText(selected_pet_name)
        elif self.allyRadio.isChecked():
            self.allyRadio.setText(selected_pet_name)
# endregion

# region show_msg
    def _show_error(self, title, message):
        """显示错误对话框"""
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setText(title)
        msg.setInformativeText(message)
        msg.setWindowTitle("错误")
        msg.exec_()
# endregion   